package utils

import (
	"fmt"
	"github.com/gocolly/colly/v2"
	"golang.org/x/net/html"
	"log"
	"strconv"
	"strings"
)

// 院校专业信息子标签
const DepartmentTagNameChild = "div"

const DepartmentTagKeyChild = "class"

const DepartmentTagValueChild = "title"

const DepartmentTagDataChild = "专业介绍"

// 专业类目请求地址
const DepartmentPrefixURL = "https://yz.chsi.com.cn/sch/schoolInfo--schId-"
const DepartmentSuffixURL = ".dhtml"

// https://yz.chsi.com.cn/sch/schoolInfo--schId-367878.dhtml
/**
**
				<a href="/sch/listYzZyjs--schId-367878,categoryId-692157514.dhtml" target="_blank">
                    <div class="icon">
                        <img src="https://t1.chei.com.cn/yz/assets/images/sch/sch-yxgk-3.svg">
                    </div>
                    <div class="title">专业介绍</div>
                </a>
**/

// 获取类目id
func GetRequestCategoryIdValue(schId int64) int64 {
	c := colly.NewCollector()
	var hrefList []string
	c.OnHTML("a[href]", func(e *colly.HTMLElement) {
		link := e.Attr("href")
		hrefList = append(hrefList, link)
	})

	err := c.Visit(DepartmentPrefixURL + strconv.FormatInt(schId, 10) + DepartmentSuffixURL)
	if err != nil {
		fmt.Println("Error:", err)
	}

	hrefList = FindString(hrefList, "/sch/listYzZyjs--schId-"+strconv.Itoa(int(schId))+",categoryId-")

	if hrefList == nil {
		log.Println("schId： " + strconv.Itoa(int(schId)) + "未获取到对应的专业类目id")
		return 0
	}

	categoryId, err := GetCategoryId(hrefList[0])
	return categoryId
}

// 获取父标签返回节点 <a>标签
func GetParentTag(n *html.Node, tagName string) *html.Node {
	if n.Type == html.ElementNode && n.Data == tagName { // 假设我们要找的是<p>标签
		// 找到<p>标签后，返回其父标签
		return n.Parent
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		if p := GetParentTag(c, tagName); p != nil {
			return p
		}
	}
	return nil
}

/*
	查询匹配元素的字符串列表
*/
func FindString(array []string, searchStr string) []string {
	// 示例 href 列表
	//hrefList := []string{
	//	"https://example.com/page1",
	//	"https://example.com/page2",
	//	"https://anotherexample.com/page3",
	//	"https://example.com/page4",
	//}

	// 过滤包含特定字符串的元素
	var filteredLinks []string
	for _, href := range array {
		if strings.Contains(href, searchStr) {
			filteredLinks = append(filteredLinks, href)
		}
	}
	return filteredLinks
}
